package com.springapi.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

public class FileToBase64 {

    public static String encodeFileToBase64Binary(File file) {
        String encodedFile = null;
        try (FileInputStream fileInputStreamReader = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            fileInputStreamReader.read(bytes);
            encodedFile = Base64.getEncoder().encodeToString(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return encodedFile;
    }

    public static void main(String[] args) {
        // 指定要转换的文件路径
        String filePath = "path/to/your/file.txt";
        File file = new File(filePath);

        // 将文件转换为Base64编码字符串
        String base64EncodedString = encodeFileToBase64Binary(file);

        // 输出Base64编码字符串
        if (base64EncodedString != null) {
            System.out.println("Base64 Encoded String: " + base64EncodedString);
        } else {
            System.out.println("Failed to encode file.");
        }
    }
}